//
//  FeedbackView.m
//  DaJiang
//
//  Created by sally on 16/9/30.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CheckStatusViewController.h"
#import "FeedbackView.h"
#import "NoteBookViewController.h"

@interface FeedbackView ()

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleLblTopLyt;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (nonatomic, readonly) FeedbackType showType;

@end

@implementation FeedbackView

- (void)initControl {
  self.bgView.layer.cornerRadius = GLargeCornerRadius;
  self.bgView.layer.masksToBounds = YES;
  self.titleLblTopLyt.constant = 25;
  self.contentLabel.preferredMaxLayoutWidth = self.bgView.width - GNormalMargin * 2;
  
  switch (self.showType) {
    case FeedbackType_Reward: //悬赏
      self.titleLabel.text = @"提交成功";
      self.contentLabel.font = GFontWithSize(GSmallFontSize);
      self.contentLabel.text = @"系统将根据您的问题及悬赏金额，寻找适合的专家并以消息的形式通知到您。";
      self.iconImage.image = [UIImage imageNamed:@"pop_reward_ic"];
      self.titleLblTopLyt.constant = 20;
      [self.sureBtn setTitle:@"我知道了" forState:UIControlStateNormal];
      break;
    case FeedbackType_Customized: //私人定制
      self.titleLabel.text = @"提交成功";
      self.contentLabel.text = @"大匠会第一时间与您联系";
      self.iconImage.image = [UIImage imageNamed:@"pop_customized_ic"];
      [self.sureBtn setTitle:@"我知道了" forState:UIControlStateNormal];
      break;
    case FeedbackType_Notebook: //阅读专家手册
      self.titleLabel.text = @"确认提交审核";
      self.contentLabel.text = @"已阅读专家手册";
      self.iconImage.image = [UIImage imageNamed:@"pop_notebook_ic"];
      [self.sureBtn setTitle:@"确定" forState:UIControlStateNormal];
      self.isReadBtn.hidden = NO;
      self.contentLabel.userInteractionEnabled = YES;
      break;
    case FeedbackType_OrderWrite: //预约-填写完
      self.titleLabel.text = @"提交成功";
      self.contentLabel.text = @"请等候专家的反馈";
      self.iconImage.image = [UIImage imageNamed:@"pop_order_write_ic"];
      [self.sureBtn setTitle:@"我知道了" forState:UIControlStateNormal];
      break;
    case FeedbackType_OrderRemind: //预约-提醒专家
      self.titleLabel.text = @"已提醒";
      self.contentLabel.text = @"请耐心等候";
      self.iconImage.image = [UIImage imageNamed:@"pop_order_remind_ic"];
      [self.sureBtn setTitle:@"我知道了" forState:UIControlStateNormal];
      break;
    case FeedbackType_OrderComment: //预约-评论
      self.titleLabel.text = @"评价已提交";
      self.contentLabel.text = @"感谢您的预约";
      self.iconImage.image = [UIImage imageNamed:@"pop_order_comment_ic"];
      [self.sureBtn setTitle:@"回到首页" forState:UIControlStateNormal];
      break;
    default:
      break;
  }
  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoNoteBookVc)];
  [self.contentLabel addGestureRecognizer:tap];
}

- (instancetype)initWithFeedbackType:(FeedbackType)type {
  //FIXME: 为什么非得user size classes的设置，才能显示在window中。
  //FIXME: 为什么file‘s owner 中的class不指定，在关联控件时就不会出现两种选择。
  NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"FeedbackView" owner:nil options:nil];
  self = nibArray[0];
  
  if (self) {
    _showType = type;
    [self initControl];
    //缓存申请信息，确保阅读专家手册再进入弹框时，有申请数据。
    [[CacheManager shareInstance]cacheLastBecomeExpert:self.becomeExpertModel];
  }
  return self;
}

- (void)show {
  UIWindow *window = [UIApplication sharedApplication].keyWindow;
  [window addSubview:self];
  self.translatesAutoresizingMaskIntoConstraints = NO;
  [[CommonMethod sharedCommonMethod] setEdge:window view:self edgeInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}

- (void)showFeedbackInView:(UIView *)viewT {
  BOOL needAdd = true;
  for (UIView *view in viewT.subviews) {
    if ([view isKindOfClass:[self class]]) {
      needAdd = false;
      break;
    }
  }
  if (needAdd == true) {
    [viewT addSubview:self];
    self.translatesAutoresizingMaskIntoConstraints = NO;
    [[CommonMethod sharedCommonMethod] setEdge:viewT view:self edgeInset:UIEdgeInsetsMake(0, 0, 0, 0)];
  }
}

- (void)hideFeedbackView {
  [self removeFromSuperview];
}

+ (void)hideFeedbackViewInView:(UIView *)viewT {
  for (UIView *view in viewT.subviews) {
    if ([view isKindOfClass:[self class]]) {
      [view removeFromSuperview];
    }
  }
}

+ (void)hideFeedbackViewWithType:(FeedbackType)type {
  UIWindow *window = [UIApplication sharedApplication].keyWindow;
  for (UIView *view in window.subviews) {
    if ([view isKindOfClass:[self class]]) {
      FeedbackView *popoverView = (FeedbackView *) view;
      if (popoverView.showType == type) {
        [popoverView removeFromSuperview];
      }
    }
  }
}

//点击确定按钮
- (IBAction)actionOnSure:(id)sender {
  if (self.showType == FeedbackType_Notebook) { //阅读专家手册后跳转到审核状态页
    [self applyExpert];
  }else if (self.showType == FeedbackType_OrderComment){//评论后跳回首页
    [[[CommonMethod sharedCommonMethod]getCurrNavController]popToRootViewControllerAnimated:YES];
    //跳转首页。需要延时一下，否则tab会空白
    [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(gotoTabOne) userInfo:nil repeats:NO];
  }else if (self.showType == FeedbackType_OrderWrite ||self.showType == FeedbackType_OrderRemind ){//预约填写完或提醒完专家调回上级页面
    [[[CommonMethod sharedCommonMethod]getCurrNavController]popToRootViewControllerAnimated:YES];
  }else if (self.showType == FeedbackType_Reward){//悬赏后跳回上级页面
    [[[CommonMethod sharedCommonMethod]getCurrNavController]popToRootViewControllerAnimated:YES];
  }
  
  [self hideFeedbackView];
}

//点击阅读按钮
- (IBAction)actionOnRead:(id)sender {
  self.isReadBtn.selected = !self.isReadBtn.isSelected;
}

//跳转专家手册页
- (void)gotoNoteBookVc {
  [self hideFeedbackView];
  NoteBookViewController *vc = [[NoteBookViewController alloc] init];
  [[[CommonMethod sharedCommonMethod] getCurrNavController] pushViewController:vc animated:YES];
}

//回到首页
- (void)gotoTabOne {
  [OperationManager gotoTabOne];
}

//申请成为专家
- (void)applyExpert {
  UIWindow *window = [UIApplication sharedApplication].keyWindow;

  if (self.isReadBtn.isSelected) {
    [[CommonMethod sharedCommonMethod] createProgressHUDInView:window withMessage:@""];
    //图片上传完了才提交审核
    
    //上传头图
    [PicModel uploadPicWithImage:self.headImage completion:^(PicModel *pic) {
      if (pic) {
        self.becomeExpertModel.bgPic = pic.original_pic;
        
        //上传身份证图片
        [PicModel uploadPicWithImage:self.idCardImageArr[0] completion:^(PicModel *pic) {
          if (pic) {
            self.becomeExpertModel.idCardPic = pic.original_pic;
            
            //上传资质图片
            [PicModel uploadPicWithImage:self.qualificationImageArr[0] completion:^(PicModel *pic) {
              if (pic) {
                self.becomeExpertModel.qualificationFile = pic.original_pic;
                
                //提交审核
                [BecomeExpertModel applyExpertWithModel:self.becomeExpertModel completion:^(BOOL isSucceed) {
                  if (isSucceed) {
                    //调整审核状态页面
                    CheckStatusViewController *vc = [[CheckStatusViewController alloc] init];
                    vc.checkStatus = CheckStatus_Ing;
                    [[[CommonMethod sharedCommonMethod] getCurrNavController] pushViewController:vc animated:YES];
                    
                  } else {
                    NSError *error = [TopicModel getLastError];
                    [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
                  }
                }];
              } else {
                NSError *error = [PicModel getLastError];
                [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
              }
            }];
          } else {
            NSError *error = [PicModel getLastError];
            [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
          }
        }];
      } else {
        NSError *error = [PicModel getLastError];
        [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
      }
      [MBProgressHUD hideAllHUDsForView:window animated:YES];
    }];
    
  } else {
    [[CommonMethod sharedCommonMethod] showToastInCenter:window withMessage:@"请阅读专家手册"];
    return;
  }
}

@end
